import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import {Login} from "../../models/login";
import {showToast} from "../../util/ui";

Page({

  data: {
    defaultImg: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fi.qqkou.com%2Fi%2F1a2742296696x681526349b15.jpg&refer=http%3A%2F%2Fi.qqkou.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1649091301&t=87504dbf5cff58c147bc51f2ff452d8e',
    defaultName: '点击授权',
    hasUserInfo: false,
    userInfo: null,
    showLoading: false
  },

  onLoad(options) {
    this.scopeTrue()
  },

  //点击登录授权
  onTap(e) {
    this.setUserProfile()
  },
  //点击我的咨询
  handleConsult() {
    if (!wx.getStorageSync('scope')) {
      showToast('您还未授权！')
      return
    }
    wx.navigateTo({
      url: '../my-consulting/my-consulting',
    })
  },
  //点击我的服务
  handleService() {
    wx.navigateTo({
      url: '../my-pay/my-pay',
    })
  },
  //点击支付服务
  handlePay() {
    if (!wx.getStorageSync('scope')) {
      showToast('您还未授权！')
      return
    }
    wx.navigateTo({
      url: '../pay/pay',
    })
  },
  //点击定位
  handleLocation() {
    wx.navigateTo({
      url: '../map/map'
    })
  },
  async setUserProfile() {
    try {
      const userRes = await wx.getUserProfile({
        lang: 'zh_CN',
        desc: '用于显示用户头像和昵称',
      })
      const codeRes = await wx.login({})
      if (!codeRes.code) {
        Toast.fail('code获取失败');
        return
      }
      this.setData({
        showLoading: true
      })
      const data = {}
      data.userName = userRes.userInfo.nickName
      data.picture = userRes.userInfo.avatarUrl
      data.code = codeRes.code
      const login = await Login.doApiLogin(data)
      if (!login.code.toString().includes(('200'))) {
        Toast.fail('登录失败');
        return
      }
      wx.setStorageSync('token', login.data)

      this._getSetting()
      wx.setStorageSync('storage_info', userRes.userInfo)
      this.setData({
        userInfo: userRes.userInfo,
        hasUserInfo: true,
        showLoading: false
      })
      Toast.success('登录成功');
    } catch (e) {
      Toast.fail('拒绝了授权');
    }
  },
  scopeTrue() {
    const scope = wx.getStorageSync('scope')
    if (scope) {
      const userInfo = wx.getStorageSync('storage_info')
      this.setData({
        hasUserInfo: true,
        userInfo
      })
    }
  },
  _getSetting() {
    wx.getSetting({
      success: res1 => {
        wx.setStorageSync('scope', res1.authSetting['scope.userInfo'])
      }
    })
  },
})
